package com.luck.ssoserver.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author luo
 */
@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 返回用户信息
     *
     * @param token
     * @return
     */
    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token) {
        String userInfo = redisTemplate.opsForValue().get(token);
        return userInfo;

    }

    /**
     * 返回登录页面
     *
     * @param url
     * @param model
     * @param ssoToken
     * @return
     */
    @GetMapping("login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String ssoToken) {
        if (StringUtils.isNotBlank(ssoToken)) {
            //不为空则说明之前有人登陆过,浏览器留下了痕迹
            return "redirect:" + url + "?token=" + ssoToken;
        }
        model.addAttribute("url", url);
        return "login";
    }

    /**
     * 处理登录请求
     *
     * @param username 账号
     * @param password 密码
     * @param url
     * @param response
     * @return
     */
    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password,
                          @RequestParam("url") String url, HttpServletResponse response) {
        //此处只要用户输入账号和密码就默认为验证正确
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            //登录成功保存用户到redis
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username, 30, TimeUnit.MINUTES);
            //给当前浏览器留下一个cookie
            Cookie ssoToken = new Cookie("sso_token", uuid);
            response.addCookie(ssoToken);
            //返回之前的页面
            return "redirect:" + url + "?token=" + uuid;
        } else {
            //登录失败展示登录页
            return "login";
        }

    }

}
